var App = function () {
    var isRTL = false;
    var isIE8 = false;
    var isIE9 = false;
    var isIE10 = false;
    var sidebarWidth = 225;
    var sidebarCollapsedWidth = 35;
    var responsiveHandlers = [];
    var layoutColorCodes = {
        'blue': '#4b8df8', 'red': '#e02222', 'green': '#35aa47',
        'purple': '#852b99', 'grey': '#555555', 'light-grey': '#fafafa', 'yellow': '#ffb848'
    };

    var _getViewPort = function () {
        var e = window, a = 'inner';
        if (!('innerWidth' in window)) {
            a = 'client';
            e = document.documentElement || document.body;
        }
        return {width: e[a + 'Width'], height: e[a + 'Height']}
    }

    var handleInit = function () {

        if ($('body').css('direction') === 'rtl') {
            isRTL = true;
        }

        isIE8 = !!navigator.userAgent.match(/MSIE 8.0/);
        isIE9 = !!navigator.userAgent.match(/MSIE 9.0/);
        isIE10 = !!navigator.userAgent.match(/MSIE 10.0/);

        if (isIE10) {
            jQuery('html').addClass('ie10'); // detect IE10 version
        }

        if (isIE10 || isIE9 || isIE8) {
            jQuery('html').addClass('ie'); // detect IE10 version
        }

        var deviceAgent = navigator.userAgent.toLowerCase();
        if (deviceAgent.match(/(iphone|ipod|ipad)/)) {
            $(document).on('focus', 'input, textarea', function () {
                $('.header').hide();
                $('.footer').hide();
            });
            $(document).on('blur', 'input, textarea', function () {
                $('.header').show();
                $('.footer').show();
            });
        }
    }

    var handleSidebarState = function () {
        var viewport = _getViewPort();
        if (viewport.width < 992) {
            $('body').removeClass("page-sidebar-closed");
        }
    }

    var runResponsiveHandlers = function () {
        for (var i in responsiveHandlers) {
            var each = responsiveHandlers[i];
            each.call();
        }
    }

    var handleResponsive = function () {
        handleSidebarState();
        handleSidebarAndContentHeight();
        handleFixedSidebar();
        runResponsiveHandlers();
    }

    // initialize the layout on page load
    var handleResponsiveOnInit = function () {
        handleSidebarState();
        handleSidebarAndContentHeight();
    }

    // handle the layout reinitialization on window resize
    var handleResponsiveOnResize = function () {
        var resize;
        if (isIE8) {
            $(window).resize(function () {
                if (resize) {
                    clearTimeout(resize);
                }
                resize = setTimeout(function () {
                    handleResponsive();
                }, 50); // wait 50ms until window resize finishes.
            });
        } else {
            $(window).resize(function () {
                if (resize) {
                    clearTimeout(resize);
                }
                resize = setTimeout(function () {
                    handleResponsive();
                }, 50); // wait 50ms until window resize finishes.
            });
        }
    }

    var handleSidebarAndContentHeight = function () {

        var content = $('.page-content');
        var sidebar = $('.page-sidebar');
        var jf = $(".J_iframe");
        var body = $('body');
        var height;

        if (body.hasClass("page-footer-fixed") === true
            && body.hasClass("page-sidebar-fixed") === false) {
            var available_height = $(window).height() - $('.footer').outerHeight();
            if (content.height() < available_height) {
                content.attr('style', 'min-height:' + available_height + 'px !important;padding:0px');
            }
        } else {
            if (body.hasClass('page-sidebar-fixed')) {
                height = _calculateFixedSidebarViewportHeight();
            } else {
                height = sidebar.height() + 20;
            }
            if (height >= content.height()) {
                content.attr('style', 'min-height:' + height + 'px !important;');
                content.css("padding", "0px");
                jf.css('min-height', height);
                jf.css("height", height);
                jf.css('width', '100%');
            } else {
                content.attr('style', 'min-height:' + height + 'px !important;');
                content.css("padding", "0px");
                jf.css('min-height', height);
                jf.css("height", height);
                jf.css('width', '100%');
            }
        }
    }

    // Handle sidebar menu
    var handleSidebarMenu = function () {
        jQuery('.page-sidebar').on('click', 'li > a', function (e) {
            if ($(this).next().hasClass('sub-menu') == false) {
                if ($('.btn-navbar').hasClass('collapsed') == false) {
                    $('.btn-navbar').click();
                }
                return;
            }
            if ($(this).hasClass('J_menuItem')) {
                return;
            }

            if ($(this).next().hasClass('sub-menu.always-open')) {
                return;
            }

            var parent = $(this).parent().parent();
            var the = $(this);

            parent.children('li.open').children('a').children('.arrow').removeClass('open');
            parent.children('li.open').children('.sub-menu').slideUp(200);
            parent.children('li.open').removeClass('open');

            var sub = jQuery(this).next();
            var slideOffeset = -200;
            var slideSpeed = 200;

            if (sub.is(":visible")) {
                jQuery('.arrow', jQuery(this)).removeClass("open");
                jQuery(this).parent().removeClass("open");
                sub.slideUp(slideSpeed, function () {
                    if ($('body').hasClass('page-sidebar-fixed') == false
                        && $('body').hasClass('page-sidebar-closed') == false) {
                        App.scrollTo(the, slideOffeset);
                    }
                    handleSidebarAndContentHeight(false);
                });
            } else {
                jQuery('.arrow', jQuery(this)).addClass("open");
                jQuery(this).parent().addClass("open");
                sub.slideDown(slideSpeed, function () {
                    if ($('body').hasClass('page-sidebar-fixed') == false
                        && $('body').hasClass('page-sidebar-closed') == false) {
                        App.scrollTo(the, slideOffeset);
                    }
                    handleSidebarAndContentHeight();
                });
            }

            e.preventDefault();
        });
    }

    var _calculateFixedSidebarViewportHeight = function () {
        var sidebarHeight = $(window).height() - $('.header').height() - $(".content-tabs").height()
            + 1;
        if ($('body').hasClass("page-footer-fixed")) {
            $(".footer").css("background-color", "#28303b");
            sidebarHeight = sidebarHeight - $('.footer').outerHeight() - 5;
        } else {
            sidebarHeight = sidebarHeight - $('.footer').outerHeight() - 5;
        }

        return sidebarHeight;
    }

    // Handles fixed sidebar
    var handleFixedSidebar = function () {
        var menu = $('.page-sidebar-menu');

        if (menu.parent('.slimScrollDiv').size() === 1) {
            menu.slimScroll({destroy: true});
            menu.removeAttr('style');
            $('.page-sidebar').removeAttr('style');
        }

        if ($('.page-sidebar-fixed').size() === 0) {
            handleSidebarAndContentHeight();
            return;
        }

        var viewport = _getViewPort();
        if (viewport.width >= 992) {
            var sidebarHeight = _calculateFixedSidebarViewportHeight() + $(".content-tabs").height();
            if (!$("body").is(".page-sidebar-closed")) {
                $(".content-tabs").css("margin-left", " 225px");
            }
            $("#menuleft").css("float", "left");
            menu.slimScroll({
                size: '7px', color: '#a1b2bd', opacity: .3,
                position: isRTL ? 'left' : 'right', height: sidebarHeight, allowPageScroll: false,
                disableFadeOut: false
            });
            handleSidebarAndContentHeight();
        } else {
            $(".content-tabs").css("margin-left", " 0px");
            $("#menuleft").css("float", "none");
        }
    }

    var handleFixedSidebarHoverable = function () {
        if ($('body').hasClass('page-sidebar-fixed') === false) {
            return;
        }
        $('.page-sidebar').off('mouseenter').on('mouseenter', function () {
            var body = $('body');
            if ((body.hasClass('page-sidebar-closed') === false || body
                    .hasClass('page-sidebar-fixed') === false)
                || $(this).hasClass('page-sidebar-hovering')) {
                return;
            }
            body.removeClass('page-sidebar-closed').addClass('page-sidebar-hover-on');
            $(this).addClass('page-sidebar-hovering');
            $(this).animate({width: sidebarWidth}, 400, '', function () {
                $(this).removeClass('page-sidebar-hovering');
            });
        });

        $('.page-sidebar').off('mouseleave').on('mouseleave', function () {
            var body = $('body');
            if ((body.hasClass('page-sidebar-hover-on') === false || body
                    .hasClass('page-sidebar-fixed') === false)
                || $(this).hasClass('page-sidebar-hovering')) {
                return;
            }
            $(this).addClass('page-sidebar-hovering');
            $(this).animate({width: sidebarCollapsedWidth}, 400, '', function () {
                $('body').addClass('page-sidebar-closed').removeClass('page-sidebar-hover-on');
                $(this).removeClass('page-sidebar-hovering');
            });
        });
    }

    var handleSidebarToggler = function () {
        var viewport = _getViewPort();
        if ($.cookie('sidebar_closed') === '1' && viewport.width >= 992) {
            $('body').addClass('page-sidebar-closed');
            $(".content-tabs").css("margin-left", " 35px");
        }

        $('.page-sidebar, .header').on('click', '.sidebar-toggler',
            function (e) {
                var body = $('body');
                var sidebar = $('.page-sidebar');

                if ((body.hasClass("page-sidebar-hover-on") && body.hasClass('page-sidebar-fixed'))
                    || sidebar.hasClass('page-sidebar-hovering')) {
                    body.removeClass('page-sidebar-hover-on');
                    sidebar.css('width', '').hide().show();
                    $.cookie('sidebar_closed', '0');
                    e.stopPropagation();
                    runResponsiveHandlers();
                    $(".content-tabs").css("margin-left", " 225px");
                    return;
                }
                $(".sidebar-search", sidebar).removeClass("open");
                if (body.hasClass("page-sidebar-closed")) {
                    body.removeClass("page-sidebar-closed");
                    if (body.hasClass('page-sidebar-fixed')) {
                        sidebar.css('width', '');
                    }
                    $(".content-tabs").css("margin-left", " 225px");
                    $.cookie('sidebar_closed', '0');
                } else {
                    body.addClass("page-sidebar-closed");
                    $.cookie('sidebar_closed', '1');
                    $(".content-tabs").css("margin-left", " 35px");
                }
                runResponsiveHandlers();
            });

    }
    var handleScrollers = function () {
        $('.scroller').each(
            function () {
                var height;
                if ($(this).attr("data-height")) {
                    height = $(this).attr("data-height");
                } else {
                    height = $(this).css('height');
                }
                $(this).slimScroll({
                    size: '7px',
                    color: ($(this).attr("data-handle-color") ? $(this).attr("data-handle-color")
                        : '#a1b2bd'),
                    railColor: ($(this).attr("data-rail-color") ? $(this).attr("data-rail-color")
                        : '#333'), position: isRTL ? 'left' : 'right', height: height,
                    alwaysVisible: ($(this).attr("data-always-visible") == "1" ? true : false),
                    railVisible: ($(this).attr("data-rail-visible") == "1" ? true : false),
                    disableFadeOut: true
                });
            });
    }

    var handleTheme = function () {
        var resetLayout = function () {
            $("body").removeClass("page-boxed").removeClass("page-footer-fixed").removeClass(
                "page-sidebar-fixed").removeClass("page-header-fixed");

            $('.header > .header-inner').removeClass("container");

            if ($('.page-container').parent(".container").size() === 1) {
                $('.page-container').insertAfter('body > .clearfix');
            }

            if ($('.footer > .container').size() === 1) {
                $('.footer').html($('.footer > .container').html());
            } else if ($('.footer').parent(".container").size() === 1) {
                $('.footer').insertAfter('.page-container');
            }

            $('body > .container').remove();
        }

        var lastSelectedLayout = '';

        var setLayout = function () {
            var layoutOption = "fluid";
            var sidebarOption = "default";
            var headerOption = "Fixed";
            var footerOption = "default";

            if (sidebarOption == "fixed" && headerOption == "default") {
                alert('Default Header with Fixed Sidebar option is not supported. Proceed with Fixed Header with Fixed Sidebar.');
                $('.header-option', panel).val("fixed");
                $('.sidebar-option', panel).val("fixed");
                sidebarOption = 'fixed';
                headerOption = 'fixed';
            }
            resetLayout(); // reset layout to default state
            if (lastSelectedLayout != layoutOption) {
                // layout changed, run responsive handler:
                runResponsiveHandlers();
            }
            lastSelectedLayout = layoutOption;
            // header
            if (headerOption === 'fixed') {
                $("body").addClass("page-header-fixed");
                $(".header").removeClass("navbar-static-top").addClass("navbar-fixed-top");
            } else {
                $("body").removeClass("page-header-fixed");
                $(".header").removeClass("navbar-fixed-top").addClass("navbar-static-top");
            }
            handleSidebarAndContentHeight(); // fix content height
            handleFixedSidebar(); // reinitialize fixed sidebar
            handleFixedSidebarHoverable(); // gongjulan lly
        }
    }
    return {
        init: function () {
            handleInit(); // initialize core variables
            handleResponsiveOnResize(); // set and handle responsive
            handleScrollers(); // handles slim scrolling contents
            handleResponsiveOnInit(); // handler responsive elements on page
            handleFixedSidebar(); // handles fixed sidebar menu
            handleFixedSidebarHoverable(); // handles fixed sidebar on hover
            handleSidebarMenu(); // handles main menu
            handleSidebarToggler(); // handles sidebar hide/show
            handleTheme(); // handles style customer tool
        },
        namePoshytip: function () {
            $('#s_mkmc').poshytip({
                content: '请输入模块名称',
                showOn: 'focus',
                // showOn: 'none',
                alignTo: 'target',
                alignX: 'inner-left',
                alignY: 'bottom',
                offsetX: 0,
                offsetY: 5
            });
            // $('#s_mkmc').on("blur", function () {
            //     $('#s_mkmc').poshytip('hide');
            // });
        },
        loadMenu: function () {
            var lay = layer.load({shade: [0.1]});
            $.ajax({
                url: ctx + "/mge/adx/userFunc?type=menu",
                dataType: 'json',
                type: 'post',
                success: function (data, sta) {
                    layer.close(lay);
                    if (data.code == 200) {
                        if (data.data.length > 0) {
                            var i = 0;
                            for (var d in data.data) {
                                var ac = "";
                                if (i == 0) {
                                    ac = "class='open'";
                                }
                                var li = $("<li " + ac + "></li>");
                                $("#pagemenu").append(li);
                                var men = data.data[d];
                                var arrow = "";
                                var ic = "";
                                if (men.tags.icon != null) {
                                    ic = '<i class= "' + men.tags.icon + '" > </i>';
                                }
                                if (men.children != null && men.children.length > 0) {
                                    var k = i == 0 ? "open" : "";
                                    arrow = '<span class="arrow ' + k + '"></span>';
                                }
                                li.append('<a href="javascript:;"> ' + ic + '<span class="title">' + men["name"] + '</span>' + arrow + '</a>');
                                if (men.children != null && men.children.length > 0) {
                                    var p = false;
                                    if (i == 0) {
                                        p = true;
                                    }
                                    dgMenu(men.children, li, p);
                                }
                                i++;
                            }
                            App.init();
                            contbals();
                        }
                    } else {
                        layer.alert("加载菜单栏失败，请重试或联系管理员！");
                    }
                }, error: function (sta) {
                    layer.close(lay);
                    layer.alert("初始化页面失败，请重试或检查网络！");
                }
            });
            $("#search_sidebar").on("submit", function (e) {
                if ($("#serbut2").css("display") == "none") {
                    return false;
                }
                var mk = $("#s_mkmc").val();
                if (mk == "") {
                    $('#s_mkmc').poshytip('show');
                    return false;
                }
                $('#s_mkmc').poshytip('hide');
                $("#serbut2").hide();
                $("#serimg2").show();
                $.ajax({
                    url: ctx + "/mge/adx/searchMenu",
                    data: $("#search_sidebar").formSerialize(),
                    dataType: 'json',
                    type: 'post',
                    timeout: 60000,
                    success: function (data, sta) {
                        $("#serbut2").show();
                        $("#serimg2").hide();
                        if (data != null && data.code == 200) {
                            var list = data.data;
                            $("#liser").remove();
                            var menu = $("#pagemenu");
                            var li = $("<li id='liser'></li>");
                            li.append('<a href="javascript:;"> <i class="fa fa fa-folder-open"> </i><span class="title">搜索结果</span><span class="arrow"></span></a>');
                            var ul = $('<ul class="sub-menu"></ul>');
                            li.append(ul);
                            ctLi(ul, list);
                            menu.append(li);
                            $("#liser a:first").trigger("click");
                        }
                    }, error: function () {
                        $("#serbut2").show();
                        $("#serimg2").hide();
                    }
                });
                return false;
            });
        },
        fixContentHeight: function () {
            handleSidebarAndContentHeight();
        },

        setLastPopedPopover: function (el) {
            lastPopedPopover = el;
        },

        addResponsiveHandler: function (func) {
            responsiveHandlers.push(func);
        },
        setEqualHeight: function (els) {
            var tallestEl = 0;
            els = jQuery(els);
            els.each(function () {
                var currentHeight = $(this).height();
                if (currentHeight > tallestEl) {
                    tallestColumn = currentHeight;
                }
            });
            els.height(tallestEl);
        },
        scrollTo: function (el, offeset) {
            pos = (el && el.size() > 0) ? el.offset().top : 0;
            jQuery('html,body').animate({scrollTop: pos + (offeset ? offeset : 0)}, 'slow');
        },
        scrollTop: function () {
            App.scrollTo();
        },
        getActualVal: function (el) {
            var el = jQuery(el);
            if (el.val() === el.attr("placeholder")) {
                return "";
            }
            return el.val();
        },
        getURLParameter: function (paramName) {
            var searchString = window.location.search.substring(1), i, val, params = searchString
                .split("&");

            for (i = 0; i < params.length; i++) {
                val = params[i].split("=");
                if (val[0] == paramName) {
                    return unescape(val[1]);
                }
            }
            return null;
        },
        isTouchDevice: function () {
            try {
                document.createEvent("TouchEvent");
                return true;
            } catch (e) {
                return false;
            }
        },
        isIE8: function () {
            return isIE8;
        },
        isIE9: function () {
            return isIE9;
        },
        isRTL: function () {
            return isRTL;
        },
        getLayoutColorCode: function (name) {
            if (layoutColorCodes[name]) {
                return layoutColorCodes[name];
            } else {
                return '';
            }
        }
    };
}();
;(function ($, window, undefined) {
    var $allDropdowns = $();
    $.fn.dropdownHover = function (options) {
        $allDropdowns = $allDropdowns.add(this.parent());
        return this.each(function () {
            var $this = $(this),
                $parent = $this.parent(),
                defaults = {
                    delay: 500,
                    instantlyCloseOthers: true
                },
                data = {
                    delay: $(this).data('delay'),
                    instantlyCloseOthers: $(this).data('close-others')
                },
                settings = $.extend(true, {}, defaults, options, data),
                timeout;

            $parent.hover(function (event) {
                if (!$parent.hasClass('open') && !$this.is(event.target)) {
                    return true;
                }

                if (settings.instantlyCloseOthers === true)
                    $allDropdowns.removeClass('open');

                window.clearTimeout(timeout);
                $parent.addClass('open');
            }, function () {
                timeout = window.setTimeout(function () {
                    $parent.removeClass('open');
                }, settings.delay);
            });

            $this.hover(function () {
                if (settings.instantlyCloseOthers === true)
                    $allDropdowns.removeClass('open');

                window.clearTimeout(timeout);
                $parent.addClass('open');
            });

            $parent.find('.dropdown-submenu').each(function () {
                var $this = $(this);
                var subTimeout;
                $this.hover(function () {
                    window.clearTimeout(subTimeout);
                    $this.children('.dropdown-menu').show();
                    $this.siblings().children('.dropdown-menu').hide();
                }, function () {
                    var $submenu = $this.children('.dropdown-menu');
                    subTimeout = window.setTimeout(function () {
                        $submenu.hide();
                    }, settings.delay);
                });
            });
        });
    };
    $(document).ready(function () {
        $('[data-hover="dropdown"]').dropdownHover();
    });
})(jQuery, this);

function ctLi(ul, dd) {
    for (var d in dd) {
        var ds = dd[d];
        var ic = "";
        if (ds.icon != null) {
            ic = '<i class= "' + ds.icon + '"></i>';
            var l = $('<li></li>');
            var a = $('<a class="J_menuItem" data-index="' + uuid() + '" href="' + ctx + ds.url + '">' + ic + ds.name + '</a>');
            a.on('click', menuItem);
            l.append(a);
            ul.append(l);
        }
    }
}

function dgMenu(ds, li, fis) {
    var pds = "";
    if (fis) {
        pds = "style='display: block;'";
    }
    var ul = $('<ul class="sub-menu" ' + pds + '></ul>');
    li.append(ul);
    for (var d in ds) {
        var m = ds[d];
        var l = "";
        var ic = "";
        if (m.tags.icon != null) {
            ic = '<i class= "' + m.tags.icon + '"></i>';
        }
        var arrow = "";
        if (m.children != null && m.children.length > 0) {
            arrow = '<span class="arrow"></span>'
        }
        if (m.strurl == "#") {
            l = '<li><a class="javascript:;" >' + ic + m.name + arrow + '</a></li>'
        } else {
            l = '<li><a class="J_menuItem" href="' + ctx + m.strurl + '">' + ic + m.name + arrow + '</a></li>';
        }
        var ll = $(l);
        ul.append(ll);
        if (m.children != null && m.children.length > 0) {
            dgMenu(m.children, ll, false);
        }
    }
}